package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.obj.BeanCopyUtil;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.dto.ProductAttributeDto;
import com.aiti.lulian.dto.ProductInfoDto;
import com.aiti.lulian.dto.SysAttachmentDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.ScaleEnterpriseService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.IProductAttributeService;
import com.aiti.lulian.service.IProductDetailedService;
import com.aiti.lulian.service.IProductService;
import com.aiti.lulian.service.ISysAttachmentService;
import com.aiti.lulian.vo.ProductInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl extends BaseSerivceImpl<ProductMapper,Product>  implements IProductService{

    private final ProductMapper productMapper;

    private final SysDictDataMapper sysDictDataMapper;

    private final IProductAttributeService attributeService;

    private final ISysAttachmentService sysAttachmentService;

    private final ProductSalesMapper productSalesMapper;

    private final LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;

    private final SysAreaMapper sysAreaMapper;

    private final ScaleEnterpriseService scaleEnterpriseService;

    private final LuLianEnterpriseMapper luLianEnterpriseMapper;

    private final IProductDetailedService productDetailedService;

    private final LuLianEnterpriseUserMapper enterpriseUserMapper;

    @Resource
    SysAttachmentMapper sysAttachmentMapper;

    public ProductServiceImpl(ProductMapper productMapper,
                              ProductSalesMapper productSalesMapper,
                              SysAreaMapper sysAreaMapper,
                              SysDictDataMapper sysDictDataMapper,
                              ScaleEnterpriseService scaleEnterpriseService,
                              LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper,
                              IProductAttributeService attributeService,
                              ISysAttachmentService sysAttachmentService,
                              LuLianEnterpriseMapper luLianEnterpriseMapper,
                              IProductDetailedService productDetailedService,
                              LuLianEnterpriseUserMapper enterpriseUserMapper) {
        this.productMapper = productMapper;
        this.attributeService = attributeService;
        this.productSalesMapper = productSalesMapper;
        this.sysAttachmentService = sysAttachmentService;
        this.enterpriseUserMapper = enterpriseUserMapper;
        this.luLianEnterpriseMapper = luLianEnterpriseMapper;
        this.productDetailedService = productDetailedService;
        this.sysAreaMapper = sysAreaMapper;
        this.sysDictDataMapper = sysDictDataMapper;
        this.scaleEnterpriseService = scaleEnterpriseService;
        this.luLianEnterpriseHistoryMapper = luLianEnterpriseHistoryMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(ProductInfoDto dto,String userId) {

        Product product = new Product();
        BeanUtil.copyProperties(dto,product,"attachments","attributes");
        //管理员
        if(StringUtils.isNotBlank(dto.getAdminRole())){
            if(StringUtils.isBlank(dto.getUscc())){
                throw new RuntimeException("没有找到统信");
            }
            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("unicode", dto.getUscc()));
            if(enterprise==null){
                throw new RuntimeException("没有找到" + dto.getUscc() + "的企业信息");
            }
            LuLianEnterprise enterpriseSx = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterprise.getBaseId()));
            if(enterpriseSx==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            product.setEnterpriseId(enterprise.getBaseId());
            product.setStatus("1");
        }else{
            product.setStatus("1");
        }


        //如果当前用户不是管理员，需要获取到自已的企业ID
        if(StringUtils.isBlank(dto.getAdminRole())){
            //查询用户所绑定的企业
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if(enterpriseUserList != null && enterpriseUserList.size() != 1){
                throw new RuntimeException("用户和企业绑定关系异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);

            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", luLianEnterpriseUser.getEnterpriseId()));
            if(enterprise==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            //保存商品基本信息
            product.setEnterpriseId(luLianEnterpriseUser.getEnterpriseId());
        }

        if(NumberUtil.isNumber(dto.getBaseNote())){
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            product.setBaseNote("");
        }
        product.setCreator(userId);
        product.setBaseCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        productMapper.insert(product);

        //保存单位
        ProductSales sales = ProductSales.builder()
                .baseId(IdUtil.simpleUUID())
                .productId(product.getBaseId())
                .unit(dto.getUnit())
                .build();
        productSalesMapper.insert(sales);
        //保存产品属性
        List<ProductAttributeDto> attributes = dto.getAttributes();
        if(attributes != null && attributes.size() > 0){
            attributes.forEach(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setProductId(product.getBaseId());
            });

            List<ProductAttribute> list = new ArrayList<ProductAttribute>();

            for(ProductAttributeDto item : attributes){
                ProductAttribute temp = new ProductAttribute();
                temp.setBaseId(item.getBaseId());
                temp.setProductId(product.getBaseId());
                temp.setBaseName(item.getBaseName());
                temp.setBaseValue(item.getBaseValue());
                list.add(temp);
            }
            if(list.size() > 0){
                attributeService.saveBatch(list);
            }
        }

        //保存图片
        List<SysAttachmentDto> attachments = dto.getAttachments();
        if(attachments != null && attachments.size() > 0){
            int i = 0;
            for(SysAttachmentDto attachment : attachments){
                attachment.setBaseId(IdUtil.simpleUUID());
                attachment.setRelId(product.getBaseId());
                if(i == 0){
                    attachment.setCategory("pic");
                }else{
                    attachment.setCategory("other");
                }
                i++;
            }
            List<SysAttachment> sysAttachments = BeanUtil.copyToList(attachments, SysAttachment.class);
            sysAttachmentService.saveBatch(sysAttachments);
        }

        //保存长图
        ProductDetailed productDetailed = productDetailedService.getOne(new QueryWrapper<ProductDetailed>().eq("product_id", product.getBaseId()));
        if(productDetailed == null){
            productDetailed = new ProductDetailed();
            productDetailed.setBaseId(IdUtil.simpleUUID());
            productDetailed.setProductId(product.getBaseId());
            productDetailed.setContent(dto.getBaseIntroduction());
        }else{
            productDetailed.setContent(dto.getBaseIntroduction());
        }
        productDetailedService.saveOrUpdate(productDetailed);

        //查询省市区所对应的名称
        //查询企业信息
        LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseHistoryMapper.selectById(product.getEnterpriseId());
        if(luLianEnterpriseHistory == null){
            throw new RuntimeException("没有找到企业信息");
        }
        List<SysArea> sysAreas = sysAreaMapper.selectList(new QueryWrapper<SysArea>().in("base_id", luLianEnterpriseHistory.getProvince(), luLianEnterpriseHistory.getCounty(), luLianEnterpriseHistory.getCity()));

        //查询行业
        SysDictData sysDictData = sysDictDataMapper.selectById(dto.getOneLevelIndustry());
        if(sysAreas != null && sysAreas.size() > 0){
            //保存产品到Search库
            ScaleSearchProductDto searchProductDto = ScaleSearchProductDto.builder()
                    .baseId(product.getBaseId())
                    .isScale("0")
                    .baseName(product.getBaseName())
                    .price(dto.getBaseNote())
                    .build();

            if(sysDictData != null){
                searchProductDto.setIndustry(sysDictData.getBaseName());
            }

            //设置省市区
            Map<String, String> areaMap = sysAreas.stream().collect(Collectors.toMap(SysArea::getBaseId, SysArea::getBaseName));
            if(areaMap.containsKey(luLianEnterpriseHistory.getProvince())){
                searchProductDto.setProvince(areaMap.get(luLianEnterpriseHistory.getProvince()));
            }
            if(areaMap.containsKey(luLianEnterpriseHistory.getCity())){
                searchProductDto.setCity(areaMap.get(luLianEnterpriseHistory.getCity()));
            }

            if(areaMap.containsKey(luLianEnterpriseHistory.getCounty())){
                searchProductDto.setCounty(areaMap.get(luLianEnterpriseHistory.getCounty()));
            }

            //设置图片
            if(attachments != null && attachments.size() > 0){
                List<SysAttachmentDto> pic = attachments.stream().filter(k -> StringUtils.equals(k.getCategory(), "pic")).collect(Collectors.toList());
                if(pic != null && pic.size() > 0){
                    searchProductDto.setPic(pic.get(0).getFullPath());
                }else{
                    SysAttachmentDto sysAttachmentDto = attachments.get(0);
                    searchProductDto.setPic(sysAttachmentDto.getFullPath());
                }
            }
            Message message = scaleEnterpriseService.addSearchProduct(searchProductDto);
            if(message.getCode() == 1){
                throw new RuntimeException("保存产品到搜索库失败");
            }
        }else{
            throw new RuntimeException("请设置该企业的省市区");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductById(ProductInfoDto dto,String userId) {
        Product product = new Product();

        BeanUtil.copyProperties(dto,product,"attachments","attributes");
        //管理员
        if(StringUtils.isNotBlank(dto.getAdminRole())){
            if(StringUtils.isBlank(dto.getUscc())){
                throw new RuntimeException("没有找到统信");
            }
            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("unicode", dto.getUscc()));
            if(enterprise==null){
                throw new RuntimeException("没有找到" + dto.getUscc() + "的企业信息");
            }

            LuLianEnterprise enterpriseSx = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterprise.getBaseId()));
            if(enterpriseSx==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            product.setEnterpriseId(enterprise.getBaseId());
        }


        //如果当前用户不是管理员，需要获取到自已的企业ID
        if(StringUtils.isBlank(dto.getAdminRole())){
            //查询用户所绑定的企业
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if(enterpriseUserList != null && enterpriseUserList.size() != 1){
                throw new RuntimeException("用户和企业绑定关系异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);

            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", luLianEnterpriseUser.getEnterpriseId()));
            if(enterprise==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            //保存商品基本信息
            product.setEnterpriseId(luLianEnterpriseUser.getEnterpriseId());
        }

        if(NumberUtil.isNumber(dto.getBaseNote())){
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            dto.setBaseNote(null);
            product.setBaseNote(null);
        }else{
            product.setPrice(null);
        }
        //修改时间为当前时间
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        productMapper.updateById(product);

        //更新图片
        //删除图片
        sysAttachmentService.remove(new QueryWrapper<SysAttachment>().eq("rel_id", product.getBaseId()));
        //重新插入图片
        //保存图片
        List<SysAttachmentDto> attachments = dto.getAttachments();
        if(attachments != null && attachments.size() > 0){
            int i = 0;
            for(SysAttachmentDto attachment : attachments){
                attachment.setBaseId(IdUtil.simpleUUID());
                attachment.setRelId(product.getBaseId());
                if(i == 0){
                    attachment.setCategory("pic");
                }else{
                    attachment.setCategory("other");
                }
                i++;
            }
            List<SysAttachment> sysAttachments = BeanUtil.copyToList(attachments, SysAttachment.class);
            sysAttachmentService.saveBatch(sysAttachments);
        }

        //删除属性
        attributeService.remove(new QueryWrapper<ProductAttribute>().eq("product_id", product.getBaseId()));
        //重新插入属性
        //保存产品属性
        List<ProductAttributeDto> attributes = dto.getAttributes();
        if(attributes != null && attributes.size() > 0){
            attributes.forEach(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setProductId(product.getBaseId());
            });
            List<ProductAttribute> list = new ArrayList<ProductAttribute>();

            for(ProductAttributeDto item : attributes){
                ProductAttribute temp = new ProductAttribute();
                temp.setBaseId(item.getBaseId());
                temp.setProductId(product.getBaseId());
                temp.setBaseName(item.getBaseName());
                temp.setBaseValue(item.getBaseValue());
                list.add(temp);
            }
            if(list.size() > 0){
                attributeService.saveBatch(list);
            }
        }

        //保存长图
        ProductDetailed productDetailed = productDetailedService.getOne(new QueryWrapper<ProductDetailed>().eq("product_id", product.getBaseId()));
        if(productDetailed == null){
            productDetailed = new ProductDetailed();
            productDetailed.setBaseId(IdUtil.simpleUUID());
            productDetailed.setProductId(product.getBaseId());
            productDetailed.setContent(dto.getBaseIntroduction());
        }else{
            productDetailed.setContent(dto.getBaseIntroduction());
        }
        productDetailedService.saveOrUpdate(productDetailed);
        //保存单位
        productSalesMapper.delete(new QueryWrapper<ProductSales>().eq("product_id", product.getBaseId()));
        ProductSales sales = ProductSales.builder()
                .baseId(IdUtil.simpleUUID())
                .productId(product.getBaseId())
                .unit(dto.getUnit())
                .build();
        productSalesMapper.insert(sales);

//查询省市区所对应的名称
        //查询企业信息
        LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseHistoryMapper.selectById(product.getEnterpriseId());
        if(luLianEnterpriseHistory == null){
            throw new RuntimeException("没有找到企业信息");
        }
        List<SysArea> sysAreas = sysAreaMapper.selectList(new QueryWrapper<SysArea>().in("base_id", luLianEnterpriseHistory.getProvince(), luLianEnterpriseHistory.getCounty(), luLianEnterpriseHistory.getCity()));

        //查询行业
        SysDictData sysDictData = sysDictDataMapper.selectById(dto.getOneLevelIndustry());
        if(sysAreas != null && sysAreas.size() > 0){
            //保存产品到Search库
            ScaleSearchProductDto searchProductDto = ScaleSearchProductDto.builder()
                    .baseId(product.getBaseId())
                    .isScale("0")
                    .baseName(product.getBaseName())
                    .price(dto.getBaseNote())
                    .build();

            if(sysDictData != null){
                searchProductDto.setIndustry(sysDictData.getBaseName());
            }

            //设置省市区
            Map<String, String> areaMap = sysAreas.stream().collect(Collectors.toMap(SysArea::getBaseId, SysArea::getBaseName));
            if(areaMap.containsKey(luLianEnterpriseHistory.getProvince())){
                searchProductDto.setProvince(areaMap.get(luLianEnterpriseHistory.getProvince()));
            }
            if(areaMap.containsKey(luLianEnterpriseHistory.getCity())){
                searchProductDto.setCity(areaMap.get(luLianEnterpriseHistory.getCity()));
            }

            if(areaMap.containsKey(luLianEnterpriseHistory.getCounty())){
                searchProductDto.setCounty(areaMap.get(luLianEnterpriseHistory.getCounty()));
            }

            //设置图片
            if(attachments != null && attachments.size() > 0){
                List<SysAttachmentDto> pic = attachments.stream().filter(k -> StringUtils.equals(k.getCategory(), "pic")).collect(Collectors.toList());
                if(pic != null && pic.size() > 0){
                    searchProductDto.setPic(pic.get(0).getFullPath());
                }else{
                    SysAttachmentDto sysAttachmentDto = attachments.get(0);
                    searchProductDto.setPic(sysAttachmentDto.getFullPath());
                }
            }
            Message message = scaleEnterpriseService.addSearchProduct(searchProductDto);
            if(message.getCode() == 1){
                throw new RuntimeException("保存产品到搜索库失败");
            }
        }else{
            throw new RuntimeException("请设置该企业的省市区");
        }
    }

    @Override
    public List<ProductInfoVo> queryProductListByEnterpriseIdForApp(String enterpriseId) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("ISNULL(sort), sort")
                .orderByDesc("base_update_time");
        wrapper.eq("enterprise_id", enterpriseId);
        List<Product> products = productMapper.selectList(wrapper);
        List<ProductInfoVo> productInfoVos = new ArrayList<>();
        for (Product product : products) {
            ProductInfoVo productInfoVo = BeanCopyUtil.convertBean(product, ProductInfoVo.class);
            List<SysAttachment> attachments = sysAttachmentMapper.selectList(new QueryWrapper<SysAttachment>().eq("rel_id", productInfoVo.getBaseId()).orderByAsc("sort"));
            productInfoVo.setAttachments(attachments);
            productInfoVos.add(productInfoVo);
        }
        return productInfoVos;
    }

    @Override
    public void updateProductInfo(ProductInfoDto dto, String userId) {
        Product product = new Product();

        BeanUtil.copyProperties(dto,product,"attachments","attributes");
        //管理员
        if(StringUtils.isNotBlank(dto.getAdminRole())){
            if(StringUtils.isBlank(dto.getUscc())){
                throw new RuntimeException("没有找到统信");
            }
            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("unicode", dto.getUscc()));
            if(enterprise==null){
                throw new RuntimeException("没有找到" + dto.getUscc() + "的企业信息");
            }

            LuLianEnterprise enterpriseSx = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterprise.getBaseId()));
            if(enterpriseSx==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            //product.setEnterpriseId(enterprise.getBaseId());
        }


        //如果当前用户不是管理员，需要获取到自已的企业ID
        if(StringUtils.isBlank(dto.getAdminRole())){
            //查询用户所绑定的企业
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if(enterpriseUserList != null && enterpriseUserList.size() != 1){
                throw new RuntimeException("用户和企业绑定关系异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);

            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", luLianEnterpriseUser.getEnterpriseId()));
            if(enterprise==null){
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            //保存商品基本信息
            //product.setEnterpriseId(luLianEnterpriseUser.getEnterpriseId());
        }

        //修改时间为当前时间
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        productMapper.updateById(product);


    }


    @Override
    public Page<Product> queryProductList(Page<Product> page, ProductInfoDto dto,String userId) {

        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        //管理员
        if(StringUtils.isBlank(dto.getAdminRole())){
            //查询用户所绑定的企业
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
            if(enterpriseUserList != null && enterpriseUserList.size() != 1){
                throw new RuntimeException("用户和企业绑定关系异常");
            }
            LuLianEnterpriseUser luLianEnterpriseUser = enterpriseUserList.get(0);
            wrapper.eq("enterprise_id",luLianEnterpriseUser.getEnterpriseId());
        }
        if (StrUtil.isNotBlank(dto.getDeptId())) {
            wrapper.eq("dept_id", dto.getDeptId());
        }
        if(StringUtils.isNotBlank(dto.getBaseName())){
            wrapper.like("base_name",dto.getBaseName());
        }
        // 先按 sort 字段从小到大排序
        // 如果 sort 相同,则按照发布时间倒序排序
                wrapper.orderByAsc("ISNULL(sort), sort")
                        .orderByDesc("base_update_time");
        Page<Product> productPage = productMapper.selectPage(page, wrapper);
        return productPage;
    }

    @Override
    public Message showProductById(ProductInfoDto dto) {

        ProductInfoVo productInfoVo = new ProductInfoVo();
        //查询基本信息
        Product product = productMapper.selectById(dto.getBaseId());
        if(product != null){
            BeanUtil.copyProperties(product,productInfoVo);
            BigDecimal price = product.getPrice();
            if(price != null && price.compareTo(new BigDecimal(0)) != 0){
                productInfoVo.setBaseNote(price.toString());
            }
            //查询产品属性
            List<ProductAttribute> attributes = attributeService.list(new QueryWrapper<ProductAttribute>().eq("product_id", product.getBaseId()));
            if(attributes != null && attributes.size() > 0) {
                productInfoVo.setAttributes(attributes);
            }
            //查询图片
            List<SysAttachment> pics = sysAttachmentService.list(new QueryWrapper<SysAttachment>().eq("rel_id", product.getBaseId()));
            productInfoVo.setAttachments(pics);
            //查询单位
            ProductSales sales = productSalesMapper.selectOne(new QueryWrapper<ProductSales>().eq("product_id", product.getBaseId()));
            if(sales != null){
                productInfoVo.setUnit(sales.getUnit());
            }
            //管理员
            if(StringUtils.isNotBlank(dto.getAdminRole())){
                String enterpriseId = product.getEnterpriseId();
                if(StringUtils.isNotBlank(enterpriseId)){
                    LuLianEnterprise enterprise = luLianEnterpriseMapper.selectById(enterpriseId);
                    if(enterprise != null){
                        productInfoVo.setUscc(enterprise.getUnicode());
                    }
                }
            }
        }
        return Message.success(productInfoVo);
    }


}
